import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { useAuthStore } from './auth'

export const useCartStore = defineStore('cart', () => {
    const authStore = useAuthStore()
    const items = ref([])

    const totalItems = computed(() => {
        return items.value.reduce((total, item) => total + item.quantity, 0)
    })

    const totalPrice = computed(() => {
        return items.value.reduce((total, item) => total + (parseFloat(item.price) * item.quantity), 0)
    })

    // 添加商品到购物车
    function addToCart(product, quantity = 1) {
        if (!authStore.isLoggedIn) {
            throw new Error('请先登录后再添加商品到购物车')
        }

        const existingItem = items.value.find(item => item.id === product.id)

        if (existingItem) {
            existingItem.quantity += quantity
        } else {
            items.value.push({
                ...product,
                quantity: quantity,
                addedAt: new Date().toISOString()
            })
        }

        // 保存到本地存储
        saveCartToStorage()
    }

    // 从购物车移除商品
    function removeFromCart(productId) {
        items.value = items.value.filter(item => item.id !== productId)
        saveCartToStorage()
    }

    // 更新商品数量
    function updateQuantity(productId, quantity) {
        const item = items.value.find(item => item.id === productId)
        if (item) {
            item.quantity = quantity
            saveCartToStorage()
        }
    }

    // 清空购物车显示（不删除数据）
    function clearCartDisplay() {
        items.value = []
    }

    // 清空购物车数据
    function clearCart() {
        items.value = []
        if (authStore.user?.id) {
            localStorage.removeItem(`cart_${authStore.user.id}`)
        }
    }

    // 保存购物车到本地存储
    function saveCartToStorage() {
        if (authStore.user?.id) {
            localStorage.setItem(`cart_${authStore.user.id}`, JSON.stringify(items.value))
        }
    }

    // 加载用户购物车
    function loadUserCart() {
        if (authStore.user?.id) {
            const savedCart = localStorage.getItem(`cart_${authStore.user.id}`)
            if (savedCart) {
                items.value = JSON.parse(savedCart)
            } else {
                items.value = []
            }
        }
    }

    // 初始化购物车
    function initCart() {
        if (authStore.isLoggedIn) {
            loadUserCart()
        } else {
            items.value = []
        }
    }

    return {
        items,
        totalItems,
        totalPrice,
        addToCart,
        removeFromCart,
        updateQuantity,
        clearCart,
        clearCartDisplay,
        saveCartToStorage,
        loadUserCart,
        initCart
    }
})